package com.njust.diary.Controlller;

import com.alibaba.fastjson.JSON;
import com.njust.diary.po.NoteType;
import com.njust.diary.po.User;
import com.njust.diary.service.NoteTypeService;
import com.njust.diary.util.JsonUtil;
import com.njust.diary.vo.Result;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.geom.RectangularShape;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/type")
public class NoteTypeServlet extends HttpServlet {
    private NoteTypeService typeService =new NoteTypeService();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String actionName =req.getParameter("actionName");
        if("query".equals(actionName)){
            typeList(req,resp);

        }else if("delete".equals(actionName)){
            deteleType(req,resp);

        }else if("addOrUpdate".equals(actionName)){
            addOrUpdate(req,resp);

        }
    }

    private void deteleType(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     String typeId = req.getParameter("typeId");
        Result<NoteType> result =typeService.deteleType(typeId);
       JsonUtil.toJson(resp,result);//页面无跳转刷新

    }

    private void typeList(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        User user =(User) req.getSession().getAttribute("user");
        List<NoteType> typeList =typeService.findTypeList(user.getUserId());
        req.setAttribute("typeList",typeList);
        req.setAttribute("changePage","type/list.jsp");
        req.setAttribute("menupage","type");
        req.getRequestDispatcher("index.jsp").forward(req,resp);

    }

    private void addOrUpdate(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {

        String typeName =req.getParameter("typeName");
        String typeId =req.getParameter("typeId");
        User user =(User) req.getSession().getAttribute("user");
        Result<Integer> result =typeService.addOrUpdate(typeName,user.getUserId(),typeId,user.getUname());
        JsonUtil.toJson(resp,result);//页面无跳转刷新


    }

}
